package cn.scy.business.service;

import cn.hutool.core.util.StrUtil;
import cn.scy.business.domain.entity.SysUser;
import cn.scy.business.mapper.SysUserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 关于 token 的相关服务
 *
 * @author scy
 */
@Service
public class GetTokenService {

    @Resource
    private SysUserMapper sysUserMapper;

    public SysUser getUserByToken(HttpServletRequest request) {
        String headerToken = request.getHeader("uuToken");
        if (headerToken == null) {
            return null;
        }
        Claims claims = Jwts.parser().setSigningKey("yunqi").parseClaimsJws(headerToken).getBody();
        String id = (String) claims.get("id");
        return sysUserMapper.selectById(id);
    }

    public String getUserIdByToken(HttpServletRequest request) {
        String headerToken = request.getHeader("uuToken");
        if (headerToken == null) {
            return null;
        }
        Claims claims = Jwts.parser().setSigningKey("yunqi").parseClaimsJws(headerToken).getBody();
        return (String) claims.get("id");
    }

    /**
     * 检查是否为管理员
     *
     * @param request request
     * @return true 是管理员，false 不是管理员
     */
    public boolean checkAdmin(HttpServletRequest request) {
        SysUser sysUser = getUserByToken(request);
        return StrUtil.equals("0", sysUser.getUserType());
    }

}
